import pygame
import random
import os
from constants import *
from tank import Tank
from bullet import Bullet

class Game:
    def __init__(self):
        # 初始化游戏状态
        self.player = None
        self.enemy = None
        self.bullets = None
        self.start_time = None
        self.game_over = None
        self.winner = None
        self.stats = None
        self.post_game_state = None  # 新增：游戏结束后的状态

        # 初始化字体
        pygame.font.init()
        self.result_font = pygame.font.SysFont('SimSun', RESULT_FONT_SIZE)
        self.stats_font = pygame.font.SysFont('SimSun', STATS_FONT_SIZE)

        # 初始化声音
        pygame.mixer.init()
        self.background_music = pygame.mixer.Sound(os.path.join('sound', 'background.mp3'))
        self.fire_sound = pygame.mixer.Sound(os.path.join('sound', 'fire.mp3'))
        self.accelerate_sound = pygame.mixer.Sound(os.path.join('sound', 'accelerate.mp3'))
        self.background_music.set_volume(0.5)  # 设置背景音乐音量
        self.fire_sound.set_volume(1.0)  # 设置开火音效音量
        self.accelerate_sound.set_volume(0.7)  # 设置加速音效音量
        self.play_background_music()

        self.reset_game()


    def play_background_music(self):
        """播放背景音乐"""
        self.background_music.play(-1)  # -1表示循环播放

    def play_accelerate_sound(self):
        """播放加速音效"""
        if not pygame.mixer.get_busy():
            self.accelerate_sound.play()

    def stop_accelerate_sound(self):
        """停止加速音效"""
        self.accelerate_sound.stop()

    def reset_game(self):
        """重置游戏状态"""
        # 创建玩家坦克（屏幕中下方）
        self.player = Tank(WINDOW_WIDTH//2,
                         WINDOW_HEIGHT * 0.8,
                         PLAYER_COLOR,
                         is_player=True)

        # 创建敌方坦克（屏幕上半部分随机位置）
        self.enemy = Tank(random.randint(TANK_WIDTH, WINDOW_WIDTH-TANK_WIDTH),
                        random.randint(TANK_HEIGHT, WINDOW_HEIGHT//2),
                        ENEMY_COLOR,
                        is_player=False)

        # 游戏状态
        self.bullets = []  # 所有炮弹
        self.start_time = pygame.time.get_ticks()
        self.game_over = False
        self.winner = None
        self.post_game_state = None  # 重置游戏结束后的状态

        # 统计数据
        self.stats = {
            'player': {'shots': 0, 'hits': 0},
            'enemy': {'shots': 0, 'hits': 0}
        }

        # 重新播放背景音乐
        self.play_background_music()

    def update(self):
        """更新游戏状态"""
        if self.game_over:
            if self.post_game_state == "player_win":
                # 我方胜利，敌方停止移动
                self.player.update(can_move=True, can_fire=False)
            elif self.post_game_state == "enemy_win":
                # 敌方胜利，双方都可以移动但不能发射
                self.player.update(can_move=True, can_fire=False)
                self.enemy.update(can_move=True, can_fire=False)
            return

        current_time = pygame.time.get_ticks()
        game_time = (current_time - self.start_time) // 1000  # 转换为秒

        # 检查游戏是否超时
        if game_time >= GAME_DURATION:
            self.end_game()
            return

        # 更新炮弹
        self._update_bullets()

        # 更新坦克状态
        _, player_moving = self.player.update()
        enemy_fired, enemy_moving = self.enemy.update()

        # 处理玩家坦克声音
        if player_moving:
            self.play_accelerate_sound()
        else:
            self.stop_accelerate_sound()

        # 处理敌方坦克声音
        if enemy_moving:
            self.play_accelerate_sound()
        else:
            self.stop_accelerate_sound()

        # 处理敌方坦克开火声音
        if enemy_fired:
            self.fire_sound.play()

        # 检查游戏是否结束
        if self.player.health <= 0 or self.enemy.health <= 0:
            self.end_game()

    def _update_bullets(self):
        """更新所有炮弹状态"""
        active_bullets = []
        for bullet in self.bullets:
            if bullet.update():
                # 检查玩家坦克碰撞
                if not bullet.is_player_bullet:
                    damage = bullet.check_collision(self.player)
                    if damage > 0:
                        self.player.take_damage(damage)
                        self.stats['enemy']['hits'] += 1
                        continue

                # 检查敌方坦克碰撞
                if bullet.is_player_bullet:
                    damage = bullet.check_collision(self.enemy)
                    if damage > 0:
                        self.enemy.take_damage(damage)
                        self.stats['player']['hits'] += 1
                        continue

                active_bullets.append(bullet)

        self.bullets = active_bullets

    def handle_player_input(self):
        """处理玩家输入"""
        if self.game_over and self.post_game_state != "player_win":
            return

        keys = pygame.key.get_pressed()

        # 移动控制
        is_moving = False
        if keys[KEY_UP]:
            self.player.move(forward=True)
            is_moving = True
        if keys[KEY_DOWN]:
            self.player.move(forward=False)
            is_moving = True
        if keys[KEY_LEFT]:
            self.player.rotate(clockwise=False)
            is_moving = True
        if keys[KEY_RIGHT]:
            self.player.rotate(clockwise=True)
            is_moving = True

        # 播放或停止加速音效
        if is_moving:
            self.play_accelerate_sound()
        else:
            self.stop_accelerate_sound()

        # 炮管控制
        if keys[KEY_CANNON_LEFT]:
            self.player.rotate_cannon(clockwise=False)
        if keys[KEY_CANNON_RIGHT]:
            self.player.rotate_cannon(clockwise=True)

        # 发射控制
        if not self.game_over and keys[KEY_FIRE] and self.player.can_fire():
            self._fire_bullet(self.player)
            self.stats['player']['shots'] += 1

    def _fire_bullet(self, tank):
        """发射炮弹"""
        bullet_pos = tank.fire()
        if bullet_pos:
            x, y, angle = bullet_pos
            self.bullets.append(Bullet(x, y, angle, tank.is_player))
            self.fire_sound.play()

    def draw(self, screen):
        """绘制游戏画面"""
        # 绘制坦克
        self.player.draw(screen)
        self.enemy.draw(screen)

        # 绘制炮弹
        for bullet in self.bullets:
            bullet.draw(screen)

        # 绘制状态信息
        self._draw_status(screen)

        # 如果游戏结束，绘制结果
        if self.game_over:
            self._draw_game_over(screen)

    def _draw_status(self, screen):
        """绘制状态信息"""
        # 计算剩余时间
        current_time = pygame.time.get_ticks()
        elapsed_time = (current_time - self.start_time) // 1000
        remaining_time = max(0, GAME_DURATION - elapsed_time)

        # 绘制时间
        time_text = self.stats_font.render(f"时间: {remaining_time}秒", True, (0, 0, 0))
        time_rect = time_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT - 30))
        screen.blit(time_text, time_rect)

        # 绘制敌方信息（左下角）
        enemy_text = self.stats_font.render(
            f"敌： 生命: {self.enemy.health}  弹药: {self.enemy.ammo}",
            True, ENEMY_COLOR
        )
        screen.blit(enemy_text, (10, WINDOW_HEIGHT - 30))

        # 绘制玩家信息（右下角）
        player_text = self.stats_font.render(
            f"我： 生命: {self.player.health}  弹药: {self.player.ammo}",
            True, PLAYER_COLOR
        )
        player_rect = player_text.get_rect(right=WINDOW_WIDTH - 10)
        player_rect.bottom = WINDOW_HEIGHT - 10
        screen.blit(player_text, player_rect)

    def _draw_game_over(self, screen):
        """绘制游戏结束画面"""
        # 确定胜者
        if not self.winner:
            if self.player.health > self.enemy.health:
                self.winner = "我方胜利！"
            elif self.player.health < self.enemy.health:
                self.winner = "敌方胜利！"
            else:
                self.winner = "平局！"

        # 绘制结果，敌方胜利时为深灰色，我方胜利时为红色，平局时为黑色
        result_color = (64, 64, 64) if self.winner == "敌方胜利！" else (255, 0, 0) if self.winner == "我方胜利！" else (0, 0, 0)
        result_text = self.result_font.render(self.winner, True, result_color)
        result_rect = result_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 - 120))
        screen.blit(result_text, result_rect)

        # 绘制统计数据
        stats_y = WINDOW_HEIGHT//2
        stats_items = [
            "生命值",
            "发射炮弹",
            "命中炮弹",
            "命中率"
        ]

        # 计算命中率
        player_accuracy = (self.stats['player']['hits'] / self.stats['player']['shots'] * 100
                         if self.stats['player']['shots'] > 0 else 0)
        enemy_accuracy = (self.stats['enemy']['hits'] / self.stats['enemy']['shots'] * 100
                        if self.stats['enemy']['shots'] > 0 else 0)

        stats_values = [
            (self.enemy.health, self.player.health),
            (self.stats['enemy']['shots'], self.stats['player']['shots']),
            (self.stats['enemy']['hits'], self.stats['player']['hits']),
            (f"{enemy_accuracy:.1f}%", f"{player_accuracy:.1f}%")
        ]

        for item, values in zip(stats_items, stats_values):
            # 绘制项目名称（中间）
            item_text = self.stats_font.render(item, True, (0, 0, 0))
            item_rect = item_text.get_rect(center=(WINDOW_WIDTH//2, stats_y))
            screen.blit(item_text, item_rect)

            # 绘制敌方数据（左侧，蓝色）
            enemy_text = self.stats_font.render(str(values[0]), True, ENEMY_COLOR)
            enemy_rect = enemy_text.get_rect(right=item_rect.left - 50)
            enemy_rect.centery = stats_y
            screen.blit(enemy_text, enemy_rect)

            # 绘制玩家数据（右侧，红色）
            player_text = self.stats_font.render(str(values[1]), True, PLAYER_COLOR)
            player_rect = player_text.get_rect(left=item_rect.right + 50)
            player_rect.centery = stats_y
            screen.blit(player_text, player_rect)

            stats_y += 30

    def end_game(self):
        """结束游戏"""
        self.game_over = True
        if self.player.health > self.enemy.health:
            self.post_game_state = "player_win"
        elif self.player.health < self.enemy.health:
            self.post_game_state = "enemy_win"
        else:
            self.post_game_state = "draw"

        # 停止所有音效
        pygame.mixer.stop()